package top.yangyitao.service.impl;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Service;

import top.yangyitao.service.CacheService;
import top.yangyitao.utils.Cache;
import top.yangyitao.utils.DateUtil;

@Service
public class CacheServiceImpl implements CacheService {

	private Map<String,Cache> cacheMap = new ConcurrentHashMap<String,Cache>();
	
	private static final int SAFEMIN = 6;//6min---5 is the timeWorker stop time,one for safe work
	
	@Override
	public void clearOutTimeCache(Date currentDate){
		cacheMap.forEach((objectName,cache)->{
			if(cache.isExpire(currentDate)) {
				cacheMap.remove(objectName);
			}
		});
	}
	
	@Override
	public Cache get(String prefix, String key) {
		return cacheMap.get(prefix+":"+key);
	}

	@Override
	public void put(String prefix, String key, Object value, Date expireDate) {
		Date safeDate = DateUtil.addMins(expireDate, -SAFEMIN);
		Date date = new Date();
		if(safeDate.before(date))
			return;//unsafe
		Cache cache = new Cache();
		cache.object = value;
		cache.expiration = safeDate;
		cacheMap.put(prefix+":"+key, cache);
	}

	@Override
	public void put(String prefix, String key, Cache cache) {
		cacheMap.put(prefix+":"+key, cache);
	}

	@Override
	public Object getValue(String prefix, String key) {
		Cache cache = cacheMap.get(prefix+":"+key);
		return cache == null?null:cache.object;
	}

}
